<template>
  <div class="article">
    <div class="row">
      <el-input
        v-model="searchArticleId"
        type="number"
        style="width: 240px; margin-right: 12px"
        placeholder="请输入文章编号"
      />
      <el-button type="primary" @click="search">查找</el-button>
    </div>
    <el-button @click="add" type="primary" style="margin: 12px 0 12px 0"
      >新增</el-button
    >
    <el-table
      :data="
        showTableData.slice(
          (currentPage - 1) * pageSize,
          currentPage * pageSize
        )
      "
      row-key="id"
      @filter-change="handlerFilterChange"
    >
      <el-table-column prop="id" label="id" column-key="id" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="time" label="时间" />
      <el-table-column
        prop="type"
        label="文章类型"
        column-key="articleType"
        :filters="typeFilter"
        :filter-method="filterType"
      />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="view(scope.row)"
            >查看详情</el-button
          >
          <el-button link type="primary" size="small" @click="edit(scope.row)"
            >编辑</el-button
          >
          <el-button
            link
            type="primary"
            size="small"
            @click="deleteArticle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin: 10px"
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="showTableData.length"
      v-model:current-page="currentPage"
    />

    <el-dialog
      center
      top="5vh"
      width="70%"
      v-model="editVisible"
      :title="editorType === 'add' ? '新增文章' : '编辑文章'"
    >
      <edit_articleVue :type="editorType" ref="editArticle" />
      <template #footer>
        <span>
          <el-button type="primary" @click="saveArticle"> 保存 </el-button>
          <el-button @click="editVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog center top="5vh" width="70%" v-model="viewArticleVisible">
      <view_articleVue ref="viewArticle" />
      <template #footer>
        <span>
          <el-button @click="viewArticleVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/stores'
import edit_articleVue from './edit_article.vue'
import view_articleVue from './view_article.vue'
const userStore = useUserStore()
// 是否显示编辑弹窗
const editVisible = ref(false)
// 是否显示文章详情弹窗
const viewArticleVisible = ref(false)
// 可以筛选的类别，一般由后端传回，但为了方便这里直接定死
const typeFilter = ref([
  {
    text: '党建工作',
    value: '党建工作',
  },
  {
    text: '研究会动态',
    value: '研究会动态',
  },
  {
    text: '行业风采',
    value: '行业风采',
  },
  {
    text: '通知公告',
    value: '通知公告',
  },
  {
    text: '示范推广',
    value: '示范推广',
  },
  {
    text: '会员活动',
    value: '会员活动',
  },
  {
    text: '会员须知',
    value: '会员须知',
  },
  {
    text: '行业动态',
    value: '行业动态',
  },
  {
    text: '公示公告',
    value: '公示公告',
  },
  {
    text: '政策法规',
    value: '政策法规',
  },
  {
    text: '招商信息',
    value: '招商信息',
  },
  {
    text: '下载申请表',
    value: '下载申请表',
  },
])
// const elTable = ref(null)
// 表格的所有数据
const tableData = ref<any>([])
// 表格展示的数据，如筛选后的，是tableDate的部分数据
const showTableData = ref<any>([])
const filterTags = ref([]) //筛选标签
const editArticle = ref<InstanceType<typeof edit_articleVue>>()
const viewArticle = ref<InstanceType<typeof view_articleVue>>()
const editorType = ref('add') //新增文章或者编辑文章
const searchArticleId = ref() //查找的文章编号
// 一般是后端做分页，本项目是前端做的
const currentPage = ref(1)
const pageSize = ref(15)
const getAllArticles = () => {
  // 获取所有文章
  axios
    .get('/api/getAllEssay', {
      headers: {
        Authorization: `Bearer ${userStore.token}`,
      },
    })
    .then((res) => {
      tableData.value = res.data.data
      getNewShowTableData()
      console.log(showTableData.value)
    })
}

// 根据id获取文章
const getArticleById = (id: any) => {
  if (id === '' || id === undefined || id === null) {
    getAllArticles()
    return
  }
  axios
    .get('/api/getEssayById', {
      headers: {
        Authorization: `Bearer ${userStore.token}`,
      },
      params: {
        id: id,
      },
    })
    .then((res) => {
      showTableData.value = []
      showTableData.value.push(res.data.data)
    })
    .catch(() => {
      showTableData.value = []
    })
}

const filterType = (value: string, row: any, column: any) => {
  const property = column['property']
  return row[property] === value
}

const search = () => {
  getArticleById(searchArticleId.value)
}

const add = () => {
  editorType.value = 'add'
  editVisible.value = true
  //el-dialog是懒加载，弹框开启时DOM还没有完全加载完成，不使用nextTick会导致ref元素editArticle渲染失败
  nextTick(() => {
    editArticle.value?.init()
  })
}

const view = (article: any) => {
  viewArticleVisible.value = true

  nextTick(() => {
    console.log(article.title)
    console.log(viewArticle.value)
    viewArticle.value?.setArticle(article)
  })
}

const edit = (article: any) => {
  editVisible.value = true
  editorType.value = 'edit'
  nextTick(() => {
    editArticle.value?.setArticle(article)
  })
}

const saveArticle = async () => {
  let saveSuccess = await editArticle.value?.save()
  if (saveSuccess) {
    editVisible.value = false
  }
  getAllArticles()
}

const deleteArticle = (id: any) => {
  ElMessageBox.confirm('你确定要删除该文章吗？此操作不可逆', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete('/api/delEssay', {
          data: {
            id: id,
          },
        })
        .then(() => {
          getAllArticles()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        })
        .catch(() => {
          ElMessage({
            type: 'error',
            message: '删除失败',
          })
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 获取新的展示数据
const getNewShowTableData = () => {
  if (filterTags.value.length === 0) {
    showTableData.value = tableData.value
  } else {
    showTableData.value = tableData.value.filter((item: any) => {
      for (let i = 0; i < filterTags.value.length; i++) {
        if (item.type === filterTags.value[i]) return true
      }
      return false
    })
  }
}

// elementUI的table筛选的钩子函数
const handlerFilterChange = (filter: any) => {
  console.log(filter)
  filterTags.value = filter['articleType']
  getNewShowTableData()
}

onMounted(() => {
  getAllArticles()
})
</script>

<style scoped>
.article {
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 10px;
  padding: 24px;
}
.tabs {
  padding: 12px 24px 24px 24px;
}
</style>
